package com.rabbit.mq.handler;

import com.rabbit.mq.annotation.QN;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @version V1.0.0
 * @ClassName: {@link HandlerContext}
 * @Description: 处理区容器
 * @author: Lanzhou
 * @date: 2021/3/19 9:46
 * @Copyright:2020 All rights reserved.
 */
@Component
public class HandlerContext {

    /**
     * 处理器存储器
     */
    private Map<String, QueueHandler> handlers = new HashMap<>();

    @Resource
    private ApplicationContext ac;

    /**
     * 初始化前加载数据
     */
    @PostConstruct
    public void init() {
        Map<String, QueueHandler> beans = ac.getBeansOfType(QueueHandler.class);
        Class<?> clazz = null;
        String className = null;
        try {
            for (QueueHandler value : beans.values()) {
                className = value.getClass().getName();
                clazz = Class.forName(className);
                String key = clazz.getAnnotation(QN.class).value();
                handlers.put(key, value);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取处理器
     *
     * @param queueName 队列名字
     * @return
     */
    public QueueHandler getHandler(String queueName) {
        QueueHandler handler = handlers.get(queueName);
        if (null == handler) {
            throw new RuntimeException("未找到对应队列的处理器");
        }
        return handler;
    }

}
